package com.wms.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wms.annotation.MyLog;
import com.wms.entity.StorePurchase;
import com.wms.entity.StorePurchaseDTO;
import com.wms.listener.StorePurchaseListener;
import com.wms.service.StorePurchaseService;
import com.wms.util.DateUtils;
import com.wms.util.R;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author TianWenHe
 * @date 2025/4/27
 * @desc 采购入库
 */
@RestController
@RequestMapping("/store/purchase")
public class StorePurchaseController {
    private Logger logger = LogManager.getLogger(StorePurchaseController.class);

    @Autowired
    private StorePurchaseService storePurchaseService;

    /**
     * 分页查询采购入库记录
     */
    @GetMapping("/find")
    @MyLog(value = "分页查询采购入库记录", type = "查询")
    public R find(StorePurchaseDTO storePurchaseDTO) {
        logger.info("分页查询采购入库记录");
        PageHelper.startPage(storePurchaseDTO.getPageNum(), storePurchaseDTO.getPageSize());
        List<StorePurchase> storePurchases = storePurchaseService.find(storePurchaseDTO);
        return R.ok(new PageInfo<>(storePurchases));
    }

    /**
     * 新增采购入库记录
     */
    @PostMapping("/add")
    @MyLog(value = "新增采购入库记录", type = "新增")
    public R add(@RequestBody StorePurchase storePurchase) {
        logger.info("新增采购入库记录");
        Long id = storePurchaseService.add(storePurchase);
        return R.ok(id);
    }

    /**
     * 修改采购入库记录
     */
    @PutMapping("/update")
    @MyLog(value = "修改采购入库记录", type = "修改")
    public R update(@RequestBody StorePurchase storePurchase) {
        logger.info("修改采购入库记录");
        storePurchaseService.update(storePurchase);
        return R.ok();
    }

    /**
     * 批量删除采购入库记录
     */
    @DeleteMapping("/delete")
    @MyLog(value = "批量删除采购入库记录", type = "删除")
    public R delete(@RequestParam List<Long> ids){
        logger.info("批量删除采购入库记录");
        storePurchaseService.delete(ids);
        return R.ok();
    }

    /**
     * 批量导入采购入库记录
     */
    @PostMapping("/import")
    @MyLog(value = "批量导入采购入库记录", type = "导入")
    public R importExcel(MultipartFile file) throws IOException {
        logger.info("批量导入采购入库记录");
        EasyExcel.read(file.getInputStream(), StorePurchase.class, new StorePurchaseListener(storePurchaseService)).sheet().doRead();
        return R.ok();
    }

    /**
     * 导出采购入库记录
     */
    @GetMapping("/export")
    @MyLog(value = "导出采购入库记录", type = "导出")
    public void export(HttpServletResponse response) throws IOException {
        logger.info("导出采购入库记录");

        // 查询全部采购入库记录
        List<StorePurchase> storePurchases = storePurchaseService.find(new StorePurchaseDTO());

        // 所有不为空的时间减8小时，这样Excel表中的时间才与数据库时间一致
        for (StorePurchase storePurchase : storePurchases) {
            if (storePurchase.getCreateTime() != null) {
                storePurchase.setCreateTime(DateUtils.subtractFixedEightHours(storePurchase.getCreateTime()));
            }
            if (storePurchase.getStorageTime() != null) {
                storePurchase.setStorageTime(DateUtils.subtractFixedEightHours(storePurchase.getStorageTime()));
            }
            if (storePurchase.getReceivingTime() != null) {
                storePurchase.setReceivingTime(DateUtils.subtractFixedEightHours(storePurchase.getReceivingTime()));
            }
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("采购入库记录", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 写入 Excel 并下载
        EasyExcel.write(response.getOutputStream(), StorePurchase.class)
                .autoCloseStream(Boolean.FALSE)
                .sheet("采购入库记录")
                .doWrite(storePurchases);
    }
}
